"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   :  闰年2月数据库正常
Create At   : 2020/10/12
Owner       : @peilinqian
Description :
    1、设置操作系统时间为2020-02-28 23:58:00
    2、客户端持续写入数据，其中一列为数据库now()方法生成的时间
    3、等待到29号，观察数据库时间一列是否正确
    4、恢复到正常时间
Expect      :
    1、操作系统时间设置成功
    2、数据生成成功
    3、数据库新插入数据时间正确
    4、恢复操作系统时间成功
History     :
    Modified by @peilinqian 2021/1/22: 增加ntp服务安装步骤,及tpcc执行开始前先删除tpcc相应result
    Modified by @peilinqian 2021/3/23: 增加环境时区修复步骤
"""
import os
import unittest
from yat.test import Node
import time
from yat.test import macro
import sys
import datetime

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *

logger = Logger()
common = Common()
commonshpri = CommonSH('PrimaryDbUser')


class ModifyConnection(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    db_primary_root_node = Node(node='PrimaryRoot')
    dbStandby1RootNode = Node(node='Standby1Root')
    DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
    DB_ENV_PATH = macro.DB_ENV_PATH
    Constant = Constant()
    CFE_PATH = macro.CFE_PATH
    TPCC_PATH = macro.TPCC_PATH

    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info("-----------reliability_os008 start-----------")
        self.tblname = 'reliability_os008'

        result = common.check_system_timezone(
            *('PrimaryRoot', 'Standby1Root', 'Standby2Root'))
        logger.info(result)
        self.assertTrue(result)

        logger.info('=====安装ntp服务=======')
        result = self.db_primary_root_node.sh('yum install -y ntp').result()
        logger.info(result)
        result = self.db_primary_root_node.sh(
            'systemctl enable ntpd').result()
        logger.info(result)
        result = self.db_primary_root_node.sh('systemctl start ntpd').result()
        logger.info(result)

    def test_modify_pidfile(self):
        logger.info('------------create table---------------------')
        result = commonshpri.executDbSql(f'drop table if exists {self.tblname};create table {self.tblname}(i int);')
        logger.info(result)
        logger.info("-----------设置操作系统时间为02/28/2020 23:59:00--------------------")
        datecmd = "date -s '02/28/2020 23:59:00';hwclock --systohc;" \
                  "service ntpd stop;ntpdate ntp.api.bz;service ntpd start"
        logger.info(datecmd)
        result = self.db_primary_root_node.sh(datecmd)
        logger.info(result)

        beforeTime = commonshpri.executDbSql('select now();')
        logger.info(beforeTime)
        self.assertIn("2020-02-28", beforeTime)

        for i in range(1, 10):
            time.sleep(10)
            result = commonshpri.executDbSql('select now();')
            logger.info(result)
            result = commonshpri.executDbSql(f'insert into {self.tblname} values(1);')
            logger.info(result)
            self.assertIn('INSERT 0 1', result)

        beforeTime = commonshpri.executDbSql('select now();')
        logger.info(beforeTime)
        self.assertIn("2020-02-29", beforeTime)

        logger.info("--------start tpcc---------")
        cmd = f"ls -al {self.TPCC_PATH}"
        logger.info(cmd)
        result = self.db_primary_root_node.sh(cmd).result()
        logger.info(result)
        if 'my_result_2020-02-29' in result:
            cmd = f"rm -rf {self.TPCC_PATH}/my_result_2020-02-29*"
            logger.info(cmd)
            result = self.db_primary_root_node.sh(cmd).result()
            logger.info(result)
        tpcc_result = common.startTPCC(
            self.db_primary_root_node, self.TPCC_PATH)
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find(self.Constant.TPCC_SUCCESS_MSG) > -1)

        afterTime = commonshpri.executDbSql('select now();')
        logger.info(afterTime)
        self.assertIn("2020-02-29", afterTime)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("-----------revert environment--------------------")
        current = self.dbStandby1RootNode.sh("date \"+%m/%d/%Y %H:%M:%S\"").result()
        logger.info(current)

        datecmd = f'date -s "{current}"'
        result = self.db_primary_root_node.sh(datecmd).result()
        logger.info(datecmd)
        logger.info(result)

        datecmd = 'hwclock --systohc;service ntpd stop;ntpdate ntp.api.bz;service ntpd start '
        result = self.db_primary_root_node.sh(datecmd).result()
        logger.info(datecmd)
        logger.info(result)
        datecmd = 'hwclock --hctosys;service ntpd stop;ntpdate ntp.api.bz;service ntpd start '
        result = self.db_primary_root_node.sh(datecmd).result()
        logger.info(datecmd)
        logger.info(result)

        logger.info('--------------------------drop table---------------------------')
        result = commonshpri.executDbSql(f'drop table if exists {self.tblname};')
        logger.info(result)
